package com.zhilianbao.leyaogo.ui.activity;

import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import com.bql.changeskin.MainTabEntity;
import com.bql.fragmentation.ControllerFragment;
import com.bql.tablayout.CommonTabLayout;
import com.bql.tablayout.listener.CustomTabEntity;
import com.bql.tablayout.listener.OnTabSelectListener2;
import com.bql.utils.EventManager;
import com.bql.utils.ThreadPool;
import com.bql.utils.ToastUtils;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.app.LeYaoGoApplication;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.events.PushEventCode;
import com.zhilianbao.leyaogo.http.api.ShoppingCartApi;
import com.zhilianbao.leyaogo.http.callback.JsonCallback;
import com.zhilianbao.leyaogo.model.response.shoppingcart.ShoppingCartGood;
import com.zhilianbao.leyaogo.ui.activity.base.BaseOkHttpActivity;
import com.zhilianbao.leyaogo.ui.fragment.goodscategory.GoodsCategoryFragment;
import com.zhilianbao.leyaogo.ui.fragment.home.HomeFragment;
import com.zhilianbao.leyaogo.ui.fragment.me.MeFragment;
import com.zhilianbao.leyaogo.ui.fragment.shoppingcart.ShoppingCartFragment;
import com.zhilianbao.leyaogo.utils.DataProviderUtils;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.dialog.CommonDialog;
import com.zhilianbao.leyaogo.view.widgets.MyRelativeLayout;
import com.zlb.lxlibrary.ui.fragment.lexiu.LeXiuFragment;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 主页
 */
public class MainActivity extends BaseOkHttpActivity {


    @BindView(R.id.main_tab_layout)
    public CommonTabLayout mMainTabLayout;

    @BindView(R.id.rl_content)
    public MyRelativeLayout mRlContent;

    public static final int POSITION_HOME = 0;//首页Position

    public static final int POSITION_CATEGORY = 1;//分类Position

    public static final int POSITION_LE_SHOW = 2;//乐秀Position

    public static final int POSITION_SHOPPING_CART = 3;//购物车Position

    public static final int POSITION_ME = 4;//我Position

    //主页Tab未选中ID数组
    private int[] mMainIconNorIds;

    //主页Tab选中ID数组
    private int[] mMainIconSelIds;

    //Tab标题数组
    private String[] mMainTitles;

    //主页Fragment数组
    private ControllerFragment[] mMainFragments;

    //Tab集合
    private ArrayList<CustomTabEntity> mMainTabs = new ArrayList<>();

    //Tab动画
    private Animation mTabAnimation = null;

    //第一次进入
    //    private boolean isFirst;

    private int currentPosition;

    //是否退出程序
    private boolean isExit;

    //定时器
    private Timer mTimer;

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        //加载Tinker补丁包
        //        if (BuildConfig.TINKER_ENABLE) {
        //            TinkerPatch.with().fetchPatchUpdate(true);
        //        }
        //        isFirst = getIntent().getBooleanExtra(IntentConfig.FIRST_SELECT_SUPPLIER, false);
        initMainTabs();
        initFragments(savedInstanceState);
        //        if (isFirst) {
        //            Utils.putLocation("深圳");
        //            Utils.putSupplierId(0);/
        //            ThreadPool.postOnUiDelayed(() -> showDefaultAddressDialog(), 1200);
        //        }
        getShoppingCartNum();
        mTimer = new Timer();
        //        Utils.registerPush();
        //        CLog.e("BUGLY_APP_CHANNEL=====" + ManifestUtils.getChannelNo(this, "BUGLY_APP_CHANNEL"));
        //        CLog.e("热修复测试");
    }


    /**
     * 退出程序
     */
    private void exit() {
        //退出程序
        if (isExit == false) {
            isExit = true;
            XToastUtils.showShortToast(getString(R.string.press_again_to_exit));
            TimerTask task = new TimerTask() {
                @Override
                public void run() {

                    isExit = false;
                }
            };
            mTimer.schedule(task, 2000);
        } else {
            if (mTimer != null) {
                mTimer.cancel();
                mTimer = null;
            }
            ToastUtils.cancel();
            finish();
            ThreadPool.shutdown();
        }
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_main;
    }


    /**
     * 初始化Tab
     */
    private void initMainTabs() {
        mTabAnimation = AnimationUtils.loadAnimation(this, R.anim.anim_main_tab);
        mMainIconNorIds = DataProviderUtils.getMainIconNorIds(this);
        mMainIconSelIds = DataProviderUtils.getMainIconSelIds(this);
        mMainTitles = DataProviderUtils.getMainTabTitles();
        for (int i = 0; i < mMainTitles.length; i++) {
            mMainTabs.add(new MainTabEntity(mMainTitles[i], mMainIconNorIds[i], mMainIconSelIds[i]));
        }
        mMainTabLayout.setTabData(mMainTabs);
        mMainTabLayout.setOnTabSelectListener(new OnTabSelectListener2() {
            @Override
            public void onTabSelect(int position, int lastPos) {
                currentPosition = position;
                switchPage(position, lastPos);
                switch (position) {
                    //首页
                    case POSITION_HOME:
                        break;

                    //分类
                    case POSITION_CATEGORY:
                        break;

                    //乐秀
                    case POSITION_LE_SHOW:
                        //                        Utils.isUserLogin(true);
                        break;

                    //购物车
                    case POSITION_SHOPPING_CART:
                        if (mMainFragments[3] != null && mMainFragments[3] instanceof ShoppingCartFragment) {
                            ((ShoppingCartFragment) mMainFragments[3]).loadData();
                        }
                        break;

                    //我
                    case POSITION_ME:
                        if (mMainFragments[4] != null && mMainFragments[4] instanceof MeFragment) {
                            ((MeFragment) mMainFragments[4]).loadRedData();
                        }
                        break;
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        //        if (Utils.isUserLogin(false)) {
        //            ShoppingCartApi.getShoppingCart(this, Utils.getUserLoginInfo().getUserId(), 1237, new JsonCallback<List<ShoppingCartGood>>(this, true) {
        //                @Override
        //                public void onSuccess(List<ShoppingCartGood> o, Call call, Response response) {
        //                    setShoppingCartNum(Utils.getShoppingCartNum(o));
        //                }
        //            });
        //        }
    }


    /**
     * 设置购物车的显示数量
     *
     * @param num
     */
    public void setShoppingCartNum(int num) {
        LeYaoGoApplication.SHOPPING_CART_NUM = num;
        mMainTabLayout.showMsg(3, num);
        EventBus.getDefault().post(new EventManager<>(LeEventCode.MSG_CODE_SET_SHOPPINGCART_SUCS));
    }

    /**
     * 切换页面
     *
     * @param curPos
     * @param lastPos
     */
    public void switchPage(int curPos, int lastPos) {
        startTabAnim(curPos, lastPos);
        showHideFragment(mMainFragments[curPos], mMainFragments[lastPos]);
    }


    /**
     * 初始化Fragment
     *
     * @param savedInstanceState
     */
    private void initFragments(Bundle savedInstanceState) {
        mMainFragments = new ControllerFragment[5];
        if (savedInstanceState == null) {
            mMainFragments[0] = HomeFragment.getInstance();
            mMainFragments[1] = GoodsCategoryFragment.getInstance();
            mMainFragments[2] = new LeXiuFragment();
            mMainFragments[3] = ShoppingCartFragment.newInstance(false);
            mMainFragments[4] = MeFragment.getInstance();
            loadMultipleRootFragment(R.id.fl_content, POSITION_HOME, mMainFragments);
        } else {
            mMainFragments[0] = findFragment(HomeFragment.class);
            mMainFragments[1] = findFragment(GoodsCategoryFragment.class);
            mMainFragments[2] = findFragment(LeXiuFragment.class);
            mMainFragments[3] = findFragment(ShoppingCartFragment.class);
            mMainFragments[4] = findFragment(MeFragment.class);
        }
    }


    /**
     * 点击Tab动画效果
     *
     * @param curPos
     * @param prePos
     */
    public void startTabAnim(int curPos, int prePos) {
        mMainTabLayout.getIconView(prePos).clearAnimation();
        mMainTabLayout.getIconView(curPos).startAnimation(mTabAnimation);
    }

    /**
     * 获取当前Tab
     *
     * @return
     */
    public int getCurrentTab() {
        return currentPosition;
    }


    /**
     * 获取购物车Tab View
     *
     * @return
     */
    public View getShopTabView() {
        return mMainTabLayout.getTabView(3);
    }

    public MyRelativeLayout getRlContent() {
        return mRlContent;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return true;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return TransitionMode.MAIN;
    }

    //    /**
    //     * 显示城市运营商对话框
    //     */
    //    private void showDefaultAddressDialog() {
    //        final NormalDialog addressDialog = new NormalDialog(this);
    //        addressDialog.content(getString(R.string.default_tips)).btnNum(1).btnText(getString(R.string.sure)).show();
    //        addressDialog.setOnBtnClickListener(() -> {
    //            addressDialog.dismiss();
    //            //            Utils.putLocation(getString(R.string.shen));
    //
    //        });
    //    }

    //切换到首页
    public void switchToHome() {
        switchPage(0, currentPosition);
        mMainTabLayout.setCurrentTab(0);
        currentPosition = 0;
    }

    //切换到我的
    public void switchToMe() {
        switchPage(4, currentPosition);
        mMainTabLayout.setCurrentTab(4);
        currentPosition = 4;
    }

    @Override
    public void onBackPressedSupport() {
        if (currentPosition != 0) {
            switchToHome();
        } else {
            exit();
        }

        //        else {
        //            moveTaskToBack(false);
        //        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("shoppingNum", LeYaoGoApplication.SHOPPING_CART_NUM);
        outState.putBoolean("gotShoppingNum", LeYaoGoApplication.HAS_GOT_SHOPPING_CART_NUM);
        outState.putInt("currentTab", currentPosition);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        LeYaoGoApplication.SHOPPING_CART_NUM = savedInstanceState.getInt("shoppingNum", 0);
        currentPosition = savedInstanceState.getInt("currentTab", 0);
        LeYaoGoApplication.HAS_GOT_SHOPPING_CART_NUM = savedInstanceState.getBoolean("gotShoppingNum", false);
    }


    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        switch (eventManager.getEventCode()) {
            case LeEventCode.MSG_CODE_PAY_FINISH:
            case LeEventCode.MSG_CODE_SWITCH_TO_HOME://去逛逛,切换进入首页
                switchToHome();
                break;

            case LeEventCode.MSG_CODE_GET_SHOPPING_CART_NUM:
            case LeEventCode.MSG_CODE_LOGIN_SUCCESS://登录成功
                getShoppingCartNum();
                break;
            case LeEventCode.MSG_CODE_SET_SHOPPINGCART_NUM:// 当购物车变化后，刷新数据
                int cartNum = (int) eventManager.getData();
                setShoppingCartNum(cartNum);
                break;

            case PushEventCode.MSG_CODE_MI_PUSH:
                //                AccountApi.registerPush(this, Utils.getUserLoginInfo().getUserId(), Utils.getUserLoginInfo().getUserAlias(), PushConfig.MI_PUSH_APP_ID, MiPushClient.getRegId(MyApplication.getContext()), new JsonCallback<Object>(Object.class) {
                //                    @Override
                //                    public void onResponse(boolean isFromCache, Object o, Request request, @Nullable Response response) {
                //                        MyApplication.getDataKeeper().put(PushConfig.PREF_KEY_MI_PUSH, true);
                //                    }
                //                });
                break;
            //            case LeEventCode.MSG_CODE_SWICH_TO_ME://设置密码成功未登录,回到我的页面
            //                switchToMe();
            //                break;
        }

    }

    /**
     * 获取购物车数量
     */
    private void getShoppingCartNum() {
        if (Utils.getUserLoginInfo() != null && !LeYaoGoApplication.HAS_GOT_SHOPPING_CART_NUM) {
            ShoppingCartApi.getShoppingCart(this, Utils.getUserLoginInfo().getUserId(), Utils.getSupplierId(), new JsonCallback<List<ShoppingCartGood>>(this, true) {
                @Override
                public void onSuccess(List<ShoppingCartGood> o, Call call, Response response) {
                    LeYaoGoApplication.HAS_GOT_SHOPPING_CART_NUM = true;
                    setShoppingCartNum(Utils.getShoppingCartNum(o));
                }
            });
        }
    }

    /**
     * 返回提示框
     */
    private void showDefaultAddressDialog() {
        CommonDialog dialog = CommonDialog.createSingleButton(getString(R.string.sure), getString(R.string.default_tips));
        dialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {

            }

            @Override
            public void right() {

            }

            @Override
            public void middle() {
                dialog.dismiss();
            }
        });
        dialog.show(getSupportFragmentManager(), "confirm_leave");
    }

    @Override
    public boolean isMainActivity() {
        return true;
    }
}
